#include <cstdlib>
#include <iostream>
#include "Common/Common.h"
#include "GameCore/Core.h"
//#include "Sound/Sound.h"

#include "Game/Logic/Scene.h"
#include "Game/Logic/Camera.h"
#include "Initializer.h"

#include <map>
#include <string>

using namespace std;
using namespace core;

static void ShowFps( float dt ) {
	printf( "FPS = %4.2f\r", 1.0f / dt );
}

static float GetDT() {
	static float t0 = 0.0f;
	static float t1 = 0.0f;

	static const float MaxDeltaT = 0.015f;
	t0 = t1;
	t1 = Framework::GetTime();
	float dt = float( t1 - t0 );
	return dt < MaxDeltaT ? dt : MaxDeltaT;
}

void Init();
void MainLoop( float dt );
void Close();

Scene* scene;

std::map<std::string, std::string> m_map;

void TestMap( std::string key, std::string val ) {
	std::map<std::string, std::string>::iterator it = m_map.find( key.c_str() );
	if( it != m_map.end() ) {
		printf( "key %s WAS found in cache\n", ( *it ).first.c_str() );
	} else {
		printf( "key %s WAS NOT found in cache\n", key.c_str() );
		m_map[key.c_str()] = val;
	}
}


int main( int, char** ) {
	try {
		Init();

		while( scene->IsActive() ) {
			MainLoop( GetDT() );
		}

		Close();
		return 0;
	}
	catch( const std::exception& ex ) {
		printf( ex.what() );
		return 0;
	}
}

void Init() {
	Framework::Create();
	Window::Create(
		Point( 100, 100 ),
		Size( 800, 600 ),
		"Title",
		Window::Mode::Windowed,
		Color::Black() );

	Window::Open();
//	sound::SoundEngine::Create();

//	core::Keyboard::AddListener( camera );
	Initializer initializer;
	scene = initializer.Initialize( "Data/Scene.json" );
}

void MainLoop( float dt ) {
	scene->Update( dt );
	scene->Render();

	Window::Update();
	ShowFps( dt );
}

void Close() {
//	sound::SoundEngine::Destroy();
	Window::Close();

	delete scene;

	Window::Destroy();
	Framework::Destroy();
}
